<template>
  <div class="setting-product" v-loading="loading" >
    <div class="setting-product-header">
      <div>
        <!-- <button type="button" class="btn btn-text setting-back-btn" @click="back"><i class="iconfont icon-arrow-left"></i> 返回</button>
        <span class="setting-header-text">|</span> -->
        <span>{{$t('common.form.setting.setCustomField')}}</span>
      </div>
      <base-button type="primary" native-type="submit" :disabled="pending"  @event="submit">{{$t('common.base.save')}}</base-button>
    </div>
   <div class="setting-product-design">
      <form-design
        v-model="fields"
        :max="maxField"
        :relation-field-options="relationOptions"
        mode="product_register"
         ref="formDesign"
      ></form-design>
    </div>
     <relation-options-modal
      ref="relationOptionsModal"
      @confirm="relationOptionsConfirm"
    >
    </relation-options-modal>
  </div>
</template>

<script>
import * as FormUtil from '@src/component/form/util';
import http from '@src/util/http';
import platform from '@src/platform';
import {   getRegisterList,
  getProductFields,
  saveRegisterList, } from '@src/api/ProductApi';
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
/* mixin */
import fieldMixin from '@src/mixins/fieldMixin';
import FormDesignMixin from '@src/mixins/formDesign';
import getProductField from '@src/modules/setting/task/taskFieldsSetting/TaskFieldsSetting';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'

// 关联字段禁用的类型
const RELATION_DISABLE_FIELDS = ['attachment', 'autograph', 'separator', 'info', 'richtext', FieldTypeMappingEnum.JsCodeBlock];
export default {
  name: 'setting-product-fields-view',
  mixins: [fieldMixin, FormDesignMixin, ThemeMixin, getProductField],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data(){
    return {
      loading: true,
      excludeFormType: ['separator', 'email', 'phone', 'radio'],
      fields: [],
      hideFields: [], // 需要隐藏并且提交时需要传给后端的字段
      pending: false,
      maxField: this.initData.fieldNum,
      relationOptions: { // 关联查询字段关联项数据
        customerFields: [],
        productFields: []
      },
    }
  },
  mounted(){
    // this.setFieldDesignHeight();

    // this.computedFormWidthAndHeight('setting-product');
    // window.addEventListener('resize', this.resizeHandler);
    this.getFieldsInfoReq()
    this.getProductFields()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler);
  },
  methods: {
      /** 
    * @description 获取产品关联查询字段关联项数据
    */
    getProductFields() {
      getProductFields({ isFromSetting: false })
        .then(res => {
          if (res.succ) {
            // 过滤自定义字段且非禁用类型
            let fields = res.data.filter(field => field.isSystem == 0 && RELATION_DISABLE_FIELDS.indexOf(field.formType) == -1);
            // 过滤不能编辑的自定义字段 不展示（是否重复报修）
            fields = fields.filter(field => field.setting?.isEdit != 0)

            fields.unshift({
              'fieldId':'serialNumber',
              'tableName':'customer',
              'fieldName':'serialNumber',
              'displayName':'产品编号',
              'isSystem':'0',
              'isSearch':'1',
              'isAppShow':'1',
              'formType':'text'
            }, {
              'fieldId':'type',
              'tableName':'customer',
              'fieldName':'type',
              'displayName':'产品类型',
              'isSystem':'0',
              'isSearch':'1',
              'isAppShow':'1',
              'formType':'select'
            })

            this.relationOptions.productFields = fields;
          }
        })
        .catch(err => console.warn(err));
    },
    back(){
      window.parent.frameHistoryBack(window)
    },
    resizeHandler(event) {
      this.computedFormWidthAndHeight('setting-product');
    },
    async submit(){
      try {
        // 合并隐藏的自定义字段数据
        this.fields = this.fields.concat(this.hideFields)
        
        let fields = FormUtil.toField(this.fields);
        
        fields.forEach(item => {
          item.tableName = 'product';
          if(item.fieldName == 'serialNumber' && item.isSystem) {
            item.setting.serialNumberUnique = (item.setting.serialNumberUnique === true);
          }
        });

        let message = FormUtil.validate(fields);
        if(!FormUtil.notification(message, this.$createElement)) return;

        this.pending = true;
     
        let result = await saveRegisterList(fields);
        if(result.status == 0){
          platform.notification({
            type: 'success',
            title: this.$t('common.base.success'),
            message: this.$t('common.form.setting.productTypeFieldUpdateSuccessTips')
          })  
          return window.location.reload()
        }

        platform.notification({
          type: 'error',
          title: this.$t('common.form.setting.productTypeFieldUpdateFailTips'),
          message: result.message
        })
      } catch (error) {
        console.error(error)
      }
      this.pending = false;
    },
    //获取产品表单属性列表
    getFieldsInfoReq() {
      getRegisterList().then((res)=>{
        const { status, data } = res;
        if( status == 0){
          const fields = data || [];
          const sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
          this.fields = FormUtil.toFormField(sortedFields);
          this.hideFields = []
          this.fields.forEach(f => {
            if(f.formType == 'relationProduct'){
              f.placeHolder = this.$t('common.form.type.relationProduct')
            }
            if (f.setting && f.setting.isEdit == 0) {
              // 保存隐藏的自定义字段
              this.hideFields.push(f)
            }
          })
          // 过滤不能编辑的自定义字段 不展示（是否重复报修）
          this.fields = this.fields.filter(field => field.setting?.isEdit != 0)
        }

        this.loading = false;
        // return getRegisterIdentification()
      })
      // .then(r=>{
      //   if(r.status === 0){
      //     this.fields.forEach((item,index)=>{
      //       if(item.fieldName == r.data.fieldName){
      //         item = r.data;
      //       }
      //     })
      //   }
      // })
      .catch(error=>{
        this.loading = false;
      });
    }
  }
}
</script>

<style lang="scss">
html,body{
  height: 100%;
}
.setting-product{
  height: 100%;
  overflow-y: hidden;
}

.setting-header-text{
  margin-right: 12px;
}

.setting-product-header{
  margin: 12px 12px 0 12px;
  padding: 10px;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  border-bottom: 1px solid #f4f7f5;
}

.setting-product-design{
  padding: 12px;
  height: calc(100% - 53px);
}

.setting-back-btn{
  i.iconfont{
    line-height: 12px;
    font-size: 12px;
  }
}

</style>
